# @Time   : 2022-03-03 17:00:00
# @Author : Gavin Jiang
# @Owner  : YSRD (Insights Value)

import json

from flask import request, g

from framework.interface.abstract_before_request import AbstractBeforeRequest


class ParamInterceptor(AbstractBeforeRequest):

    @staticmethod
    def priority():
        return 10

    def handle(self):
        # ParamInterceptor.__fill_params_to_g()
        pass

    @staticmethod
    def __fill_params_to_g():
        params = {}
        for key, value in request.args.items():
            if key == 'json':
                data = json.loads(value)
                if isinstance(data, dict):
                    params.update(data)
                else:
                    params['error'] = '不是合法的json'
                    raise ValueError('不是合法的json')
            else:
                params[key] = ParamInterceptor.__decode_if_json(value)
        # request.json: body中的raw，格式为application/json的数据
        if request.json:
            params.update(request.json)
        # request.form: body中的form-data数据
        if request.form:
            params.update(request.form)

        g.params = params

    @staticmethod
    def __decode_if_json(value: str):
        try:
            data = json.loads(value)
            return data
        except ValueError:
            return value
